package com.easy.project.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.easy.project.domain.dto.system.UserRoleDTO;
import com.easy.project.domain.po.system.SysUserRolePO;
import com.easy.project.mapper.system.SysUserRoleMapper;
import com.easy.project.service.system.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统用户角色关联表 服务实现类
 * </p>
 *
 * @author wxz
 * @since 2024-01-10
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRolePO> implements ISysUserRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userRole(UserRoleDTO userRoleDTO) {
        // 删除用户的关联关系
        remove(new LambdaQueryWrapper<SysUserRolePO>().eq(SysUserRolePO::getUserId,userRoleDTO.getUserId()));
        // 创建关联关系
        List<SysUserRolePO> sysUserRolePOList = new ArrayList<>();
        List<Long> roleIdList = userRoleDTO.getRoleIdList();
        Long userId = userRoleDTO.getUserId();
        for (Long roleId : roleIdList){
            SysUserRolePO sysUserRolePO = new SysUserRolePO();
            sysUserRolePO.setRoleId(roleId);
            sysUserRolePO.setUserId(userId);
            sysUserRolePOList.add(sysUserRolePO);
        }
        saveBatch(sysUserRolePOList);
    }
}
